using System;
using System.IO;
using Storage.Core;

namespace Storage.Server
{
	internal class StorageOperationLog : IStorageOperationLog
	{
		public StorageOperationLog(string fileName)
		{
			fileHandle = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
			fileHandle.Seek(0, SeekOrigin.End);
			serializer = BinarySerializer.BeginRecord(fileHandle);
		}

		public StorageOperationLog()
			: this (DefaultFileName) { }

		public void LogAddOrUpdateEntity(PlainEntity entity)
		{
			serializer.Write(StorageOpCodes.AddOrUpdate);
			entity.Serialize(serializer);
			fileHandle.Flush();
		}

		public void LogDeleteEntity(Guid id)
		{
			serializer.Write(StorageOpCodes.Delete);
			serializer.Write(id);
			fileHandle.Flush();
		}

		public void Dispose()
		{
			fileHandle.Close();
		}

		public const string DefaultFileName = "storage.operations.log";

		private readonly IBinarySerializer serializer;
		private readonly FileStream fileHandle;
	}
}